const api = require('../../utils/api')
const util = require('../../utils/util')

Page({
  data: {
    selectedDate: '',
    formattedDate: '',
    today: '',
    healthScore: null,
    glucoseScore: null,
    bpScore: null,
    weightScore: null,
    glucoseStatus: '',
    bpStatus: '',
    weightStatus: '',
    glucoseAvg: null,
    bpAvg: null,
    weight: null,
    glucoseCount: 0,
    bpCount: 0,
    weightTrend: '',
    healthAdvice: []
  },

  onLoad() {
    // 初始化日期
    const today = new Date()
    const todayStr = util.formatDate(today)
    const formattedDate = util.formatDateCN(today)
    
    this.setData({
      selectedDate: todayStr,
      formattedDate: formattedDate,
      today: todayStr
    })
    
    this.fetchReportData(todayStr)
  },

  onShow() {
    // 页面显示时刷新数据
    if (this.data.selectedDate) {
      this.fetchReportData(this.data.selectedDate)
    }
  },

  // 日期选择变化
  onDateChange(e) {
    const date = e.detail.value
    const formattedDate = util.formatDateCN(new Date(date))
    
    this.setData({
      selectedDate: date,
      formattedDate: formattedDate
    })
    
    this.fetchReportData(date)
  },

  // 获取健康报告数据
  async fetchReportData(date) {
    try {
      wx.showLoading({ title: '加载中...' })
      
      // 获取当日健康评分
      const scoreResult = await api.health.getHealthScore({ date })
      
      // 获取当日血糖数据
      const glucoseResult = await api.health.getDailySummary({ 
        date, 
        type: 'glucose' 
      })
      
      // 获取当日血压数据
      const bpResult = await api.health.getDailySummary({ 
        date, 
        type: 'bloodPressure' 
      })
      
      // 获取当日体重数据
      const weightResult = await api.health.getDailySummary({ 
        date, 
        type: 'weight' 
      })
      
      // 获取健康建议
      const adviceResult = await api.health.getHealthAdvice({ date })
      
      // 设置数据
      this.setData({
        healthScore: scoreResult?.overall || null,
        glucoseScore: scoreResult?.glucose?.score || null,
        bpScore: scoreResult?.bloodPressure?.score || null,
        weightScore: scoreResult?.weight?.score || null,
        glucoseStatus: this.getStatusClass(scoreResult?.glucose?.status),
        bpStatus: this.getStatusClass(scoreResult?.bloodPressure?.status),
        weightStatus: this.getStatusClass(scoreResult?.weight?.status),
        glucoseAvg: glucoseResult?.average || null,
        bpAvg: bpResult?.systolicAvg && bpResult?.diastolicAvg 
          ? `${bpResult.systolicAvg}/${bpResult.diastolicAvg}` 
          : null,
        weight: weightResult?.latest || null,
        glucoseCount: glucoseResult?.count || 0,
        bpCount: bpResult?.count || 0,
        weightTrend: this.getWeightTrend(weightResult?.trend),
        healthAdvice: adviceResult?.list || []
      })
      
      wx.hideLoading()
    } catch (err) {
      console.error('获取健康报告数据失败:', err)
      wx.hideLoading()
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      })
    }
  },

  // 获取状态对应的样式类
  getStatusClass(status) {
    const statusMap = {
      'normal': 'normal',
      'high': 'alert',
      'low': 'warning',
      'highRisk': 'alert',
      'unstable': 'warning'
    }
    return statusMap[status] || ''
  },

  // 获取体重趋势描述
  getWeightTrend(trend) {
    if (!trend) return ''
    
    const trendMap = {
      'up': '上升趋势',
      'down': '下降趋势',
      'stable': '保持稳定'
    }
    return trendMap[trend] || ''
  },

  // 分享健康日报
  shareReport() {
    wx.showActionSheet({
      itemList: ['生成分享图片', '发送给微信好友'],
      success: (res) => {
        if (res.tapIndex === 0) {
          this.generateShareImage()
        } else if (res.tapIndex === 1) {
          this.shareToWechat()
        }
      }
    })
  },

  // 生成分享图片
  generateShareImage() {
    wx.showLoading({ title: '生成图片中...' })
    
    // 这里应该调用生成图片的API
    // 示例代码，实际实现可能更复杂
    setTimeout(() => {
      wx.hideLoading()
      wx.showToast({
        title: '图片已保存到相册',
        icon: 'success'
      })
    }, 1500)
  },

  // 分享给微信好友
  shareToWechat() {
    // 在真实环境中，这会触发微信的分享功能
    wx.showToast({
      title: '请点击右上角分享',
      icon: 'none'
    })
  },

  // 页面分享配置
  onShareAppMessage() {
    return {
      title: `我的${this.data.formattedDate}健康日报`,
      path: `/pages/healthReport/healthReport?date=${this.data.selectedDate}`,
      imageUrl: '/images/share/health_report.png'
    }
  }
}) 